<?php

class Default_IrController extends Zend_Controller_Action
{
    private $usuario = null;

    public function init()
    {
       
    }

    public function indexAction()
    {
        $log = new Application_Model_DbTable_Log();
        $select = $log->select()->where('controller = "'.$this->getRequest()->getControllerName().'"')->order("horario DESC")->limit(15);

        $this->view->log = $log->fetchAll($select);      
    }
   

    public function removeAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $titudepAux = new Application_Model_DbTable_TituDep();
        $pagamentoAux = new Application_Model_DbTable_Pagamento();

        $pagamentoAux->delete(null);
        $titudepAux->delete(null);

        $data = array();
        $data['success'] = "Impostos de Renda excluídos com sucesso!";

        $json = Zend_Json::encode($data);
        echo $json;
    }

    public function cadastroAction()
    {
        $form = new Benservi_Forms_File();            

        $breadcumb_1 = $this->getRequest()->getControllerName();        
           

        $form->setAction("cadastro");          
        $breadcumb_2 = 'Upload Titulares/Dependentes';
              if ($form->isValid($this->_request->getPost())) {
                if($this->_request->isPost()){                   
                       try {
                            Benservi_Log_Log::factory("Iniciado upload Imposto de Renda", Zend_Log::INFO, $this->getRequest()->getControllerName());

                            $titudepAux = new Application_Model_DbTable_TituDep();
                            $pagamentoAux = new Application_Model_DbTable_Pagamento();

                            $pagamentoAux->delete(null);
                            $titudepAux->delete(null);

                            $form->file->receive();
                            $fp = fopen($form->file->getFileName(), "r");

                            $texto = "";
                            while (!feof($fp)){
                              $texto .= fgetc($fp);
                            }
                            fclose($fp);

                            $dados = explode(';n',$texto);

                            $atualizadoEm = date('Y-m-d H:i:s');                           
                            $lastId ='';
                            for($index = 0; $index < sizeof($dados)-1; $index++){
                                $aux = explode(";", $dados[$index]);

                                $titudep = new Application_Model_DbTable_TituDep();
                                $dataTituDep['contrato'] = trim($aux[0]);
                                $dataTituDep['cpf'] = $aux[1];
                                $dataTituDep['nome'] = $aux[2];
                                $dataTituDep['atualizadoEm'] = $atualizadoEm;
                                $dataTituDep['tipo'] = $aux[5];
                                $dataPagamento['mes_referencia'] = $aux[3];
                                $dataPagamento['valor'] = $aux[4];                                

                                if(!$titudep->getContratoNome($dataTituDep['cpf'], $dataTituDep['nome'] ) > 0)
                                {
                                     $lastId = $titudep->insert($dataTituDep);
                                }

                                if($lastId != ''){
                                    $pagamento = new Application_Model_DbTable_Pagamento();
                                    $dataPagamento['TituDep_id'] = $lastId;
                                    $pagamento->insert($dataPagamento);
                                }
                            }
                            $this->view->status = "Atualização concluída";
                       }catch (Exception $e) {
                             Benservi_Log_Log::factory($e->getMessage(), Zend_Log::INFO, $this->getRequest()->getControllerName());
                       }
              }
                Benservi_Log_Log::factory("Termino upload Imposto de Renda", Zend_Log::INFO, $this->getRequest()->getControllerName());
             }

              
        $this->view->breadcump1 = strtoupper($breadcumb_1);
        $this->view->breadcump2 = $breadcumb_2;
        
        $this->view->form = $form;
    }   


    public function consultaAction()
    {        
            
      $form = new Benservi_Forms_Consulta();
      $form->setMethod('GET');

      $this->view->breadcump1 = 'IR';
      $this->view->breadcump2 = 'Consulta';

      $titudep =  new Application_Model_DbTable_TituDep();

      if(($this->_request->isGet()) and ($this->_request->getParam('cpf') <> '')){
          //unset($this->_request->getParam('submit'));
          $formData = $this->_request->getParams();
            if ($form->isValid($formData)) {
                $select = $titudep->select()->where("cpf =".$formData['cpf']);

                $this->view->total = $titudep->fetchAll($select)->count();
                $this->view->titudep = $titudep->fetchAll($select)->current();

                $this->_request->clearParams();
            }
      }
      else{         
         $result = $titudep->select()->order('nome ASC');
         $total = $titudep->fetchAll()->count();
         $page = $this->_getParam('page', 1);
         $paginator = Zend_Paginator::factory($result);
         $paginator->setItemCountPerPage(15);
         $paginator->setCurrentPageNumber($page);
         
         $this->view->paginator = $paginator;
      }
         $this->view->form = $form;         
    }

    public function usuarioAction()
    {
        $this->_helper->layout->setLayout("layout2");
        $cpf = $this->_request->getParam('CPF');
        $pdf = $this->_request->getParam('pdf');

        $this->view->cpf = $cpf;

        //if($ano == '') $ano = date("Y");
        $ano = 2010;

        if($pdf == 'true'){
            $this->geraPdf($cpf, $ano);
        }
        else{
            if($cpf <> ''){
               $titudep =  new Application_Model_DbTable_TituDep();

               $select = $titudep->select()->where("cpf =".$cpf);
                             
               $this->view->total = $titudep->fetchAll($select)->count();
               $this->view->titudep = $titudep->fetchAll($select)->current();               
            }
            $this->view->ano = $ano;
        }        
    }

    private function geraPdf($cpf, $ano)
    {
         $pdf = Zend_Pdf::load('ir_pdf/layout_ir.pdf');
         $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
         $template = $pdf->pages[0];

         $page = new Zend_Pdf_Page($template);
         
         $page->setFont($font, 13)
             ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
             ->drawText("DEMONSTRATIVO DE PAGAMENTOS EFETUADOS EM ".$ano, 100, 680, 'UTF-8');

         $titudep =  new Application_Model_DbTable_TituDep();
         $select = $titudep->select()->where("cpf = '".$cpf."'");
         $titudepRow = $titudep->fetchAll($select)->current();        

         $tipo = ($titudepRow->tipo == 'T') ? 'Titular' : 'Dependente';

         $page->setFont($font, 11)
             ->drawLine(9, 665, 582, 665)
             ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
             ->drawText("Nome: ".$titudepRow->nome, 10, 645, 'UTF-8')
             ->drawText("Tipo: ".$tipo, 10, 630, 'UTF-8')
             ->drawText("Cpf: ".$titudepRow->cpf, 120, 630, 'UTF-8')
             ->drawText("Contrato: ".$titudepRow->contrato, 230, 630, 'UTF-8');

         $pagamento = $titudepRow->findDependentRowset('Application_Model_DbTable_Pagamento');

         $posLin = 9;
         $posText = 20;
         $total = 0;
         $totalContrato = 0;
         foreach ($pagamento as $pagamentoItens) {
            $page->setFont($font, 11)
                 ->drawLine($posLin, 617, $posLin, 585)
                 ->drawText($pagamentoItens->mes_referencia, $posText, 605)
                 ->drawText(number_format($pagamentoItens->valor , 2, ',', '.'), $posText+8, 590);
            $posLin += 80;
            $posText += 80;
            $total += $pagamentoItens->valor;
         }
         $totalContrato += $total;

         $page->setFont($font, 11)
              ->drawLine($posLin, 614, $posLin, 585)
              ->drawText('Total', $posText + 10, 605)
              ->drawText(number_format($total , 2, ',', '.'), $posText+7, 590);

          $page->setFont($font, 11)
               ->drawLine(9, 565, 582, 565);

          $titudep = new Application_Model_DbTable_TituDep();
          $select = $titudep->select()->where('contrato = ' . $titudepRow->contrato . ' and id <> ' . $titudepRow->id);
          $titudepRow = $titudep->fetchAll($select);

          $posNome = 545;
          $posOthers = 530;  
                    
          $posMesAlt = 505;
          $posValorAlt = 490;

          $posLinAltX = 517;
          $posLinAltY = 485;

          $posLinBack = 465;

          foreach ($titudepRow as $tituDepItens)
          {                
                $tipo = ($tituDepItens->tipo == 'T') ? 'Titular' : 'Dependente';
                $page->setFont($font, 11)
                     ->drawLine(9, 665, 582, 665)
                     ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
                     ->drawText("Nome: ".$tituDepItens->nome, 10, $posNome, 'UTF-8')
                     ->drawText("Tipo: ".$tipo, 10, $posOthers, 'UTF-8')
                     ->drawText("Cpf: ".$tituDepItens->cpf, 120, $posOthers, 'UTF-8');

                 $pagamento = $tituDepItens->findDependentRowset('Application_Model_DbTable_Pagamento');
                 
                 $total = 0;

                 $posLin = 9;
                 $posText = 20;

                 foreach ($pagamento as $pagamentoItens) {
                    $page->setFont($font, 11)
                         ->drawLine($posLin, $posLinAltX, $posLin, $posLinAltY)
                         ->drawText($pagamentoItens->mes_referencia, $posText, $posMesAlt)
                         ->drawText(number_format($pagamentoItens->valor , 2, ',', '.'), $posText+8, $posValorAlt);
                    $posLin += 80;
                    $posText += 80;
                    $total += $pagamentoItens->valor;
                 }
                 $totalContrato += $total;

                 $page->setFont($font, 11)
                      ->drawLine($posLin, $posLinAltX, $posLin, $posLinAltY)
                      ->drawText('Total', $posText + 10, $posMesAlt)
                      ->drawText(number_format($total, 2, ',', '.'), $posText+7, $posValorAlt);

                  $page->setFont($font, 11)
                       ->drawLine(9, $posLinBack, 582, $posLinBack);

                $posNome -= 100;
                $posOthers -= 100;

                $posMesAlt -= 100;
                $posValorAlt -= 100;

                $posLinAltX -= 100;
                $posLinAltY -= 100;

                $posLinBack -= 100;
          }

          $page->setFont($font, 18)
                      ->drawText('Total Contrato: '.number_format($totalContrato, 2, ',', '.'), 190, $posMesAlt+20);

         $pdf->pages[1] = $page;
         unset($pdf->pages[0]);        

         $extra = date("mdHhhs");
         $pdf->save('ir_pdf/'.$cpf.$extra.".pdf");

         $this->_redirect('ir_pdf/'.$cpf.$extra.".pdf");
    
    }

    public function testeAction()
    {
        
    }
  
}




